<template>
	<div class="loginWrap">
		<div class="login">
			<headers :childProp="state.parentData"></headers>
			<div class="leftTab">
				<p @click="tabFun(index)" :class="state.tabActive == index ? 'on' : ''" v-for="(item, index) in state.TabList" :key="index">
					{{ item.name }}
				</p>
			</div>
			<div class="content">
				<div class="infoWrap" v-if="state.tabActive == 0">
					<div class="fileWrap">
						<div class="header">
							<el-upload
								class="avatar-uploader"
								style="position: relative"
								:action="action"
								:headers="{ 'Platform-Name': 'avatar' }"
								list-type="picture"
								:show-file-list="false"
								:on-success="handleAvatarSuccess"
								:before-upload="beforeUpload"
							>
								<img class="camera" src="@/assets/hmm/11.png" />
								<el-avatar v-if="state.parentData.userInfo.avatar" :src="state.parentData.userInfo.avatar"></el-avatar>
								<el-avatar v-else>{{ userFirstName }}</el-avatar>
							</el-upload>
							<p>
								<span
									><i>嗨, </i><i>{{ state.parentData.userInfo.realName }}</i></span
								>
								<span>这里是个人用户信息页</span>
							</p>
						</div>
						<div class="current">当前头像</div>
					</div>
					<div class="information">
						<div class="item">
							<div class="title">
								<span></span>
								<span>用户信息</span>
							</div>
							<div class="cardList">
								<el-row :gutter="10">
									<el-col :span="6">
										<div class="col-grid"><span class="col-item-label">姓名: </span> {{ state.parentData.userInfo.realName }}</div>
									</el-col>
									<el-col :span="6">
										<div class="col-grid"><span class="col-item-label">手机号: </span>{{ state.parentData.userInfo.mobile }}</div>
									</el-col>
								</el-row>
							</div>
						</div>

						<div class="item">
							<div class="title">
								<span></span>
								<span>账户信息</span>
							</div>
							<div class="cardList">
								<el-row :gutter="10">
									<el-col :span="6">
										<div class="col-grid"><span class="col-item-label">用户名: </span>{{ state.parentData.userInfo.username }}</div>
									</el-col>
								</el-row>
							</div>
						</div>
					</div>
				</div>
				<div class="form" v-else>
					<div class="top">
						<!-- <img src="@/assets/hmm/8.png" /> -->
						<p></p>
						<p>{{ state.checkPassWord }}</p>
					</div>
					<el-form
						ref="ruleFormRef"
						label-width="80px"
						:model="ruleForm"
						status-icon
						:hide-required-asterisk="false"
						:rules="rules"
						class="demo-ruleForm"
					>
						<el-form-item prop="pass" label="原始密码">
							<el-input v-model="ruleForm.pass" type="password" placeholder="请输入原始密码" show-password />
						</el-form-item>
						<el-form-item prop="newPass" label="修改密码">
							<el-input v-model="ruleForm.newPass" type="password" placeholder="请输入修改密码" show-password />
						</el-form-item>
						<el-form-item prop="surePass" label="确认密码">
							<el-input v-model="ruleForm.surePass" type="password" placeholder="请输入确认密码" show-password />
						</el-form-item>
						<el-form-item class="btn">
							<el-button type="primary" @click="submitForm(ruleFormRef)"> 确定 </el-button>
							<el-button type="primary" @click="returnGateway"> 取消 </el-button>
							<!-- <el-button v-if="state.returnGateway == true" type="primary" @click="layOut"> 退出登录 </el-button>
							<el-button v-else type="primary" @click="returnGateway"> 返回门户 </el-button> -->
							<!-- <el-button type="primary" @click="resetForm(ruleFormRef)"> 重置 </el-button> -->
						</el-form-item>
					</el-form>
				</div>

				<div style="position: absolute; right: 10px; top: 10px">
					<el-button @click="returnGateway" type="primary">返回门户</el-button>
				</div>
			</div>
		</div>
	</div>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted, watch } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import { useRoute, useRouter } from 'vue-router'
import headers from '../hmm/components/headers.vue'
import { password, info } from '@/api/auth-hm'
import constant from '@/utils/constant'
import type { UploadProps } from 'element-plus'
import { editUserUrl } from '@/api/sys/user'
const route = useRoute()
const router = useRouter()
const state = reactive({
	checkPassWord: '登录成功! 请修改初始密码!',
	parentData: {
		route: 'userInfo',
		userInfo: {},
		isTrue: true
	},
	routeId: 1,
	returnGateway: false,
	TabList: [
		{
			name: '个人信息',
			id: '1'
		},
		{
			name: '修改密码',
			id: '2'
		}
	],
	tabActive: 0
})

const action = ref(constant.uploadUrl)

onMounted(() => {
	let user = sessionStorage.getItem('loginState')
	state.returnGateway = false

	if (route.query.active == 1) {
		state.tabActive = 1
	} else {
		state.tabActive = 0
	}
	if (user == 'true') {
		state.checkPassWord = '登录成功! 请修改初始密码!'
		state.returnGateway = true
		roleListFun()
	} else {
		state.checkPassWord = '请修改密码!'
		let userInfo = JSON.parse(sessionStorage.getItem('userInfo'))
		roleListFun(userInfo.orgId)
	}
})
// const sendState = item => {
// 	console.log(item)
// }
const tabFun = item => {
	console.log(item)
	state.tabActive = item
}
const returnGateway = item => {
	router.push({
		path: '/gateway'
	})
	// router.go(-1)
}

const userFirstName = ref('')
const roleListFun = orgId => {
	let loginForm = {
		orgId: ''
	}
	if (orgId) {
		loginForm.orgId = orgId
	}
	info(loginForm).then((res: any) => {
		if (res.code == 0) {
			sessionStorage.setItem('userInfo', JSON.stringify(res.data))
			state.parentData.userInfo = res.data

			userFirstName.value = state.parentData.userInfo.realName[0].toUpperCase()
		} else {
			ElMessage.error(res.msg)
		}
	})
}
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive<RuleForm>({
	pass: '',
	newPass: '',
	surePass: ''
})
const rules = reactive<FormRules<RuleForm>>({
	pass: [
		{ required: true, message: '请输入原始密码', trigger: 'blur' }
		// { min: 4, max: 20, message: '新密码长度为 4-20 位', trigger: 'blur' },
	],
	newPass: [
		{ required: true, message: '请输入修改密码', trigger: 'blur' },
		{
			pattern: /^(?=.*\d)(?=.*[a-zA-Z]).{8,}$/,
			message: '长度至少为8，至少包含有一个字母和一个数字',
			trigger: 'blur'
		}
	],
	surePass: [
		{ required: true, message: '请输入确认密码', trigger: 'blur' },
		{
			pattern: /^(?=.*\d)(?=.*[a-zA-Z]).{8,}$/,
			message: '长度至少为8，至少包含有一个字母和一个数字',
			trigger: 'blur'
		}
	]
})
const submitForm = async (formEl: FormInstance | undefined) => {
	if (!formEl) return
	await formEl.validate((valid, fields) => {
		if (valid) {
			if (ruleForm.pass == ruleForm.newPass) {
				ElMessage.error('原始密码和修改密码一致，请重新输入')
				return false
			} else if (ruleForm.newPass != ruleForm.surePass) {
				ElMessage.error('修改密码和确认密码不一致')
				return false
			} else {
				let loginForm = {
					password: ruleForm.pass,
					newPassword: ruleForm.newPass
				}
				password(loginForm).then((res: any) => {
					if (res.code == 0) {
						// 登录成功 获取信息放缓存
						ElMessage({
							message: '修改成功',
							type: 'success'
						})
						sessionStorage.removeItem('token')
						sessionStorage.removeItem('loginState')
						sessionStorage.removeItem('userInfoState')
						sessionStorage.removeItem('userInfo')
						sessionStorage.removeItem('platformId')
						router.push({
							path: '/login'
						})
					} else {
						ElMessage.error(res.msg)
					}
				})
			}
		} else {
			console.log('error submit!', fields)
		}
	})
}
const resetForm = (formEl: FormInstance | undefined) => {
	if (!formEl) return
	formEl.resetFields()
}
const layOut = () => {
	sessionStorage.removeItem('loginState')
	ElMessage({
		message: '退出成功',
		type: 'success'
	})
	router.push('/login')
}

const beforeUpload = file => {
	const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg'
	if (!isJpgOrPng) {
		ElMessage.error('只支持JPG、PNG格式!')
		return Promise.reject()
	}
	const isLt2M = file.size / 1024 / 1024 > 2
	if (isLt2M) {
		ElMessage.error('图片大小不能超过2MB!')
		return Promise.reject()
	}
}

const handleAvatarSuccess: UploadProps['onSuccess'] = (res, file) => {
	if (res.code !== 0) {
		ElMessage.error('上传失败：' + res.message)
		return false
	}
	console.log(res.data.url)

	if (res.data.url) {
		state.parentData.userInfo.avatar = res.data.url

		// console.log(state.parentData.userInfo)

		editUserUrl(state.parentData.userInfo.avatar).then(res => {
			roleListFun(state.parentData.userInfo.orgId)
		})
	}
	// dataForm.name = res.data.name
	// dataForm.type = res.data.suffix
	// dataForm.fileUrl = res.data.url
	// dataForm.size = res.data.size
}

watch(
	router.currentRoute.value,
	toPath => {
		console.log(router.currentRoute.value.query.active)
		if (router.currentRoute.value.query.active) {
			console.log(router.currentRoute.value.query.active)
			state.tabActive = Number(router.currentRoute.value.query.active)
		} else {
		}
	},
	{ immediate: true, deep: true }
)
</script>

<style lang="scss" scoped>
.cf {
	zoom: 1;
}
.cf::after {
	display: block;
	height: 0;
	clear: both;
	font-size: 0;
	content: '.';
	visibility: hidden;
}
.leftTab {
	position: fixed;
	left: 0;
	// top: 66px;
	top: 48px;
	height: 100vh;
	overflow: auto;
	background: #fff;
	width: 200px;
	text-align: center;
	color: #303133;
	font-size: 14px;
	z-index: 1;
	p {
		height: 40px;
		line-height: 40px;
		&:hover,
		&.on {
			color: #409eff;
			background: #ecf5ff;
			cursor: pointer;
		}
	}
}
.loginWrap {
	background: linear-gradient(to right, #e1ecf7, #e7f3ff);
	height: 100%;
	overflow: auto;
	.login {
		position: relative;
		.content {
			margin: 18px 16px 18px 216px;
			min-height: calc(100vh - 84px);
			background: #fff;
			position: relative;
			.infoWrap {
				font-size: 14px;
				.fileWrap {
					.header {
						display: flex;
						align-items: center;
						padding: 16px 16px 12px;
						.camera {
							position: absolute;
							bottom: -4px;
							right: -4px;
							display: block;
							width: 15px;
							background: #f2f3f5;
							padding: 4px;
							border-radius: 10px;
						}
						.el-avatar {
							width: 60px;
							height: 60px;
							font-size: 20px;
							background: #667afa;
						}
						p {
							display: inline-block;
							vertical-align: middle;
							position: relative;
							&:nth-child(1) {
								.camera {
									position: absolute;
									bottom: -4px;
									right: -4px;
									display: block;
									width: 15px;
									background: #f2f3f5;
									padding: 4px;
									border-radius: 10px;
								}
								.el-avatar {
									width: 60px;
									height: 60px;
									font-size: 20px;
								}
							}
							&:nth-child(2) {
								margin-left: 30px;
								span {
									display: block;
									color: #909399;
									&:nth-child(1) {
										margin-bottom: 5px;
										i {
											font-style: normal;
											font-size: 20px;
											color: #303133;
											font-weight: 700;
										}
									}
								}
							}
						}
					}
					.current {
						padding-bottom: 16px;
						margin: 0 16px;
						color: #303133;
						border-bottom: 1px solid #e4e7ed;
					}
				}
				.information {
				}
			}
			.form {
				display: inline-block;
				width: 460px;
				margin-left: 16px;
				.top {
					p {
						margin: 20px 0 0px 5px;
						font-size: 20px;
						font-weight: 700;
						color: #303133;
						display: inline-block;
						vertical-align: middle;
						&:nth-child(1) {
							width: 3px;
							height: 18px;
							background: #409eff;
						}
					}
				}
				.demo-ruleForm {
					margin-top: 32px;
					::v-deep(.el-form-item) {
						position: relative;
						padding-bottom: 10px;
						.el-form-item__label {
							color: #303133;
							&::before {
								display: none;
							}
							&::after {
								content: '*';
								color: #f56c6c;
								margin-left: 4px;
							}
						}
						.el-form-item__content {
							font-size: 0;
							.el-input__suffix {
								.el-input__validateIcon {
									display: none;
								}
							}
							.el-form-item__error {
								padding-top: 4px;
							}
							.el-button {
								background: #409eff;
								border-color: #409eff;
								font-size: 14px;
								width: calc(50% - 8px);
								display: inline-block;
								vertical-align: middle;
								height: 40px;
								&:nth-child(2) {
									margin-left: 16px;
									background: #fff;
									color: #606266;
								}
							}
						}
						&.btn {
							.el-button {
								width: 80px;
							}
						}
					}
				}
			}
		}
	}
}

.title {
	height: 38px;
	width: 100%;
	font-size: 16px;
	color: #303133;
	font-weight: 600;
	display: flex;
	align-items: center;
	padding-left: 16px;
	span:nth-child(1) {
		width: 3px;
		height: 16px;
		display: inline-block;
		background: rgba(64, 158, 255, 1);
		margin-right: 11px;
	}
}
.cardList {
	padding: 10px 16px;
	.col-item-label {
		width: 55px;
		display: inline-block;
	}
}
</style>
<style>
.el-select__popper .el-select-dropdown__item.selected {
	color: #409eff !important;
}
.el-dropdown__popper .el-dropdown-menu .el-dropdown-menu__item:hover {
	color: #409eff !important;
}
</style>
